const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const axios = require('axios');
const { query, transaction } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 文本文件类型
const TEXT_FILE_TYPES = [
  'txt', 'md', 'doc', 'docx', 'pdf', 'rtf',
  'js', 'ts', 'jsx', 'tsx', 'vue', 'html', 'css', 'scss', 'less',
  'py', 'java', 'cpp', 'c', 'cs', 'php', 'rb', 'go', 'rs', 'swift',
  'json', 'xml', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf',
  'sql', 'sh', 'bat', 'ps1', 'dockerfile',
  'log', 'csv', 'tsv'
];

// 获取文本文件内容
const getTextFileContent = async (filePath, fileName) => {
  try {
    // 从文件名中提取扩展名
    const fileExtension = path.extname(fileName).toLowerCase().substring(1);
    
    // 对于不同文件类型使用不同的读取策略
    if (['pdf', 'doc', 'docx'].includes(fileExtension)) {
      // 对于PDF和Word文档，返回文件路径，让AI直接处理
      return { content: null, filePath, fileExtension };
    } else {
      // 对于纯文本文件，直接读取内容
      const content = await fs.readFile(filePath, 'utf8');
      return { content, filePath: null, fileExtension };
    }
  } catch (error) {
    console.error('读取文件内容失败:', error);
    return { content: null, filePath: null, fileExtension: null };
  }
};

// 使用AI分析文件内容
const analyzeFileContent = async (fileName, fileType, content, filePath) => {
  try {
    const prompt = `请分析以下文件的内容，提取关键信息：

文件名：${fileName}
文件类型：${fileType}
${content ? `文件内容：\n${content.substring(0, 4000)}...` : `文件路径：${filePath}`}

请返回JSON格式的分析结果：
{
  "contentType": "text|code|document|other",
  "keywords": ["关键词1", "关键词2", "关键词3"],
  "topics": ["主题1", "主题2", "主题3"],
  "entities": ["实体1", "实体2", "实体3"],
  "summary": "内容摘要（100-200字）",
  "language": "zh|en"
}`;

    const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
      model: 'qwen-turbo',
      input: {
        messages: [
          {
            role: 'user',
            content: prompt
          }
        ]
      },
      parameters: {
        temperature: 0.3,
        max_tokens: 1000
      }
    }, {
      headers: {
        'Authorization': `Bearer ${process.env.ALIYUN_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.output && response.data.output.text) {
      let text = response.data.output.text;
      // 处理markdown代码块
      if (text.includes('```json')) {
        text = text.replace(/```json\n?/g, '').replace(/```\n?/g, '');
      }
      return JSON.parse(text);
    }
    return null;
  } catch (error) {
    console.error('AI分析文件内容失败:', error);
    return null;
  }
};

// 计算文件相似度
const calculateFileSimilarity = async (file1, file2) => {
  try {
    const prompt = `请比较以下两个文件的内容相似度：

文件1：${file1.file_name}
关键词：${JSON.stringify(file1.keywords || [])}
主题：${JSON.stringify(file1.topics || [])}
摘要：${file1.summary || ''}

文件2：${file2.file_name}
关键词：${JSON.stringify(file2.keywords || [])}
主题：${JSON.stringify(file2.topics || [])}
摘要：${file2.summary || ''}

请从以下维度评估相似度（0-1分）：
1. 主题相似度
2. 关键词重叠度
3. 内容相关性
4. 概念关联度

返回JSON格式：
{
  "similarityScore": 0.85,
  "relationshipType": "similar_to",
  "relationshipStrength": 0.8,
  "reasons": ["原因1", "原因2", "原因3"]
}

注意：relationshipType必须是以下值之一：
- "similar_to": 相似关系
- "related_to": 相关关系  
- "extends": 扩展关系
- "references": 引用关系
- "depends_on": 依赖关系`;

    const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
      model: 'qwen-turbo',
      input: {
        messages: [
          {
            role: 'user',
            content: prompt
          }
        ]
      },
      parameters: {
        temperature: 0.2,
        max_tokens: 800
      }
    }, {
      headers: {
        'Authorization': `Bearer ${process.env.ALIYUN_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.output && response.data.output.text) {
      let text = response.data.output.text;
      if (text.includes('```json')) {
        text = text.replace(/```json\n?/g, '').replace(/```\n?/g, '');
      }
      
      const result = JSON.parse(text);
      
      // 验证关系类型值
      const validTypes = ['similar_to', 'related_to', 'extends', 'references', 'depends_on'];
      if (!validTypes.includes(result.relationshipType)) {
        console.warn(`AI返回了无效的关系类型: ${result.relationshipType}，使用默认值: related_to`);
        result.relationshipType = 'related_to';
      }
      
      return result;
    }
    return null;
  } catch (error) {
    console.error('计算文件相似度失败:', error);
    // 如果API调用失败，使用模拟数据
    return calculateMockSimilarity(file1, file2);
  }
};

// 模拟相似度计算
const calculateMockSimilarity = (file1, file2) => {
  let keywords1, keywords2, topics1, topics2;
  
  try {
    keywords1 = JSON.parse(file1.keywords || '[]');
  } catch (e) {
    console.log('解析keywords1失败:', file1.keywords);
    keywords1 = [];
  }
  
  try {
    keywords2 = JSON.parse(file2.keywords || '[]');
  } catch (e) {
    console.log('解析keywords2失败:', file2.keywords);
    keywords2 = [];
  }
  
  try {
    topics1 = JSON.parse(file1.topics || '[]');
  } catch (e) {
    console.log('解析topics1失败:', file1.topics);
    topics1 = [];
  }
  
  try {
    topics2 = JSON.parse(file2.topics || '[]');
  } catch (e) {
    console.log('解析topics2失败:', file2.topics);
    topics2 = [];
  }
  
  // 计算关键词重叠度
  const commonKeywords = keywords1.filter(k => keywords2.includes(k));
  const keywordOverlap = commonKeywords.length / Math.max(keywords1.length, keywords2.length, 1);
  
  // 计算主题重叠度
  const commonTopics = topics1.filter(t => topics2.includes(t));
  const topicOverlap = commonTopics.length / Math.max(topics1.length, topics2.length, 1);
  
  // 计算文件名相似度
  const name1 = file1.file_name.toLowerCase();
  const name2 = file2.file_name.toLowerCase();
  const nameSimilarity = name1.includes(name2.split('.')[0]) || name2.includes(name1.split('.')[0]) ? 0.3 : 0;
  
  // 综合相似度
  const similarityScore = (keywordOverlap * 0.4 + topicOverlap * 0.4 + nameSimilarity * 0.2);
  
  if (similarityScore < 0.3) {
    return null; // 相似度太低，不建立关联
  }
  
  let relationshipType = 'related_to';
  if (keywordOverlap > 0.5) relationshipType = 'similar_to';
  if (name1.includes('guide') && name2.includes('guide')) relationshipType = 'similar_to';
  if (name1.includes('basics') && name2.includes('guide')) relationshipType = 'extends';
  
  const reasons = [];
  if (commonKeywords.length > 0) reasons.push(`共同关键词: ${commonKeywords.join(', ')}`);
  if (commonTopics.length > 0) reasons.push(`共同主题: ${commonTopics.join(', ')}`);
  if (nameSimilarity > 0) reasons.push('文件名相似');
  
  return {
    similarityScore: Math.min(similarityScore, 0.95),
    relationshipType: relationshipType,
    relationshipStrength: similarityScore,
    reasons: reasons.length > 0 ? reasons : ['内容相关']
  };
};

// 分析用户的所有文本文件
router.post('/analyze', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取用户的所有文本文件
    console.log('开始查询文本文件，用户ID:', userId);
    const files = await query(`
      SELECT cf.id as file_id, cf.user_id, cf.parent_id, cf.file_name, cf.file_path, cf.file_size, cf.file_type, cf.mime_type, cf.created_at, cf.updated_at,
             fca.id as analysis_id, fca.content_type, fca.extracted_text, fca.keywords, fca.topics, fca.entities, fca.summary, fca.language, fca.analysis_status
      FROM cloud_files cf
      LEFT JOIN file_content_analysis fca ON cf.id = fca.file_id
      WHERE cf.user_id = ? 
        AND cf.file_type = 'file'
        AND (cf.mime_type LIKE 'text/%' OR cf.file_name LIKE '%.txt' OR cf.file_name LIKE '%.md' OR cf.file_name LIKE '%.js' OR cf.file_name LIKE '%.py' OR cf.file_name LIKE '%.java' OR cf.file_name LIKE '%.html' OR cf.file_name LIKE '%.css' OR cf.file_name LIKE '%.json' OR cf.file_name LIKE '%.docx' OR cf.file_name LIKE '%.doc' OR cf.file_name LIKE '%.pdf')
      ORDER BY cf.created_at DESC
    `, [userId]);
    console.log('找到文本文件数量:', files.length);
    console.log('文件列表:', files.map(f => ({ file_id: f.file_id, file_name: f.file_name })));

    if (files.length === 0) {
      return res.json({
        success: true,
        message: '没有找到文本文件',
        analyzed: 0,
        total: 0
      });
    }

    let analyzedCount = 0;
    const analysisResults = [];

    for (const file of files) {
      try {
        console.log('处理文件:', file.file_name, '文件ID:', file.file_id, '分析状态:', file.analysis_status);
        
        // 如果已经分析过且状态为completed，跳过
        if (file.analysis_status === 'completed') {
          console.log('文件已分析，跳过:', file.file_name);
          analyzedCount++;
          continue;
        }

        console.log('开始分析文件:', file.file_name);
        
        // 更新分析状态为processing
        await query(
          'INSERT INTO file_content_analysis (file_id, user_id, analysis_status) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE analysis_status = ?',
          [file.file_id, userId, 'processing', 'processing']
        );

        // 获取文件内容
        console.log('读取文件内容:', file.file_path);
        const { content, filePath, fileExtension } = await getTextFileContent(file.file_path, file.file_name);
        console.log('文件内容长度:', content ? content.length : 0);
        
        // 使用AI分析内容
        console.log('开始AI分析:', file.file_name);
        const analysis = await analyzeFileContent(file.file_name, fileExtension, content, filePath);
        console.log('AI分析结果:', analysis);
        
        if (analysis) {
          // 保存分析结果
          await query(`
            UPDATE file_content_analysis 
            SET content_type = ?, extracted_text = ?, keywords = ?, topics = ?, entities = ?, summary = ?, language = ?, analysis_status = ?
            WHERE file_id = ?
          `, [
            analysis.contentType,
            content,
            JSON.stringify(analysis.keywords),
            JSON.stringify(analysis.topics),
            JSON.stringify(analysis.entities),
            analysis.summary,
            analysis.language,
            'completed',
            file.file_id
          ]);

          analysisResults.push({
            fileId: file.file_id,
            fileName: file.file_name,
            analysis: analysis
          });
          analyzedCount++;
        } else {
          // 分析失败
          await query(
            'UPDATE file_content_analysis SET analysis_status = ? WHERE file_id = ?',
            ['failed', file.file_id]
          );
        }
      } catch (error) {
        console.error(`分析文件 ${file.file_name} 失败:`, error);
        await query(
          'UPDATE file_content_analysis SET analysis_status = ? WHERE file_id = ?',
          ['failed', file.file_id]
        );
      }
    }

    res.json({
      success: true,
      message: `文件分析完成，成功分析 ${analyzedCount} 个文件`,
      analyzed: analyzedCount,
      total: files.length,
      results: analysisResults
    });
  } catch (error) {
    console.error('分析文件失败:', error);
    res.status(500).json({
      success: false,
      message: '分析文件失败'
    });
  }
});

// 构建知识图谱
router.post('/build', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    console.log('开始构建知识图谱，用户ID:', userId);
    
    // 获取已分析的文件
    const analyzedFiles = await query(`
      SELECT cf.id as file_id, cf.user_id, cf.parent_id, cf.file_name, cf.file_path, cf.file_size, cf.file_type, cf.mime_type, cf.created_at, cf.updated_at,
             fca.id as analysis_id, fca.content_type, fca.extracted_text, fca.keywords, fca.topics, fca.entities, fca.summary, fca.language, fca.analysis_status
      FROM cloud_files cf
      JOIN file_content_analysis fca ON cf.id = fca.file_id
      WHERE cf.user_id = ? AND fca.analysis_status = 'completed'
      ORDER BY cf.created_at DESC
    `, [userId]);
    console.log('找到已分析文件数量:', analyzedFiles.length);

    if (analyzedFiles.length < 2) {
      return res.json({
        success: true,
        message: '需要至少2个已分析的文件才能构建知识图谱',
        nodes: [],
        edges: []
      });
    }

    // 清空现有的关联关系
    await query('DELETE FROM file_relationships WHERE user_id = ?', [userId]);
    await query('DELETE FROM knowledge_edges WHERE user_id = ?', [userId]);
    await query('DELETE FROM knowledge_nodes WHERE user_id = ?', [userId]);

    const relationships = [];
    const nodes = [];
    const edges = [];

    // 为每个文件创建节点
    for (const file of analyzedFiles) {
      let keywords, topics;
      try {
        keywords = JSON.parse(file.keywords || '[]');
        console.log('解析keywords成功:', keywords);
      } catch (e) {
        console.log('解析keywords失败:', file.keywords);
        keywords = [];
      }
      
      try {
        topics = JSON.parse(file.topics || '[]');
        console.log('解析topics成功:', topics);
      } catch (e) {
        console.log('解析topics失败:', file.topics);
        topics = [];
      }

      const node = {
        fileId: file.file_id,
        fileName: file.file_name,
        fileType: file.file_type,
        contentType: file.content_type,
        keywords: keywords,
        topics: topics,
        summary: file.summary,
        importanceScore: 0.5 // 默认重要性分数
      };
      nodes.push(node);

      // 插入知识图谱节点
      await query(`
        INSERT INTO knowledge_nodes (user_id, node_type, node_id, node_name, node_description, node_properties, importance_score)
        VALUES (?, 'file', ?, ?, ?, ?, ?)
      `, [
        userId,
        file.file_id,
        file.file_name,
        file.summary,
        JSON.stringify({
          fileType: file.file_type,
          contentType: file.content_type,
          keywords: keywords,
          topics: topics
        }),
        0.5
      ]);
    }

    // 计算文件之间的相似度
    for (let i = 0; i < analyzedFiles.length; i++) {
      for (let j = i + 1; j < analyzedFiles.length; j++) {
        const file1 = analyzedFiles[i];
        const file2 = analyzedFiles[j];

        try {
          const similarity = await calculateFileSimilarity(file1, file2);
          
          if (similarity && similarity.similarityScore > 0.3) { // 只保留相似度大于0.3的关联
            const relationship = {
              sourceFileId: file1.file_id,
              targetFileId: file2.file_id,
              relationshipType: similarity.relationshipType,
              similarityScore: similarity.similarityScore,
              relationshipStrength: similarity.relationshipStrength,
              reasons: similarity.reasons
            };
            relationships.push(relationship);

            // 验证并转换关系类型（file_relationships表使用旧格式）
            const oldFormatTypes = ['similar', 'related', 'extension', 'reference', 'dependency'];
            const newToOldMapping = {
              'similar_to': 'similar',
              'related_to': 'related',
              'extends': 'extension',
              'references': 'reference',
              'depends_on': 'dependency'
            };
            
            let oldFormatType = newToOldMapping[similarity.relationshipType] || 'related';
            if (!oldFormatTypes.includes(oldFormatType)) {
              console.warn(`无效的旧格式关系类型: ${oldFormatType}，使用默认值: related`);
              oldFormatType = 'related';
            }
            
            // 保存到数据库
            await query(`
              INSERT INTO file_relationships (source_file_id, target_file_id, user_id, relationship_type, similarity_score, relationship_strength, relationship_reasons)
              VALUES (?, ?, ?, ?, ?, ?, ?)
            `, [
              file1.file_id,
              file2.file_id,
              userId,
              oldFormatType,
              similarity.similarityScore,
              similarity.relationshipStrength,
              JSON.stringify(similarity.reasons)
            ]);

            // 创建知识图谱边
            const sourceNodeId = await query('SELECT id FROM knowledge_nodes WHERE user_id = ? AND node_type = "file" AND node_id = ?', [userId, file1.file_id]);
            const targetNodeId = await query('SELECT id FROM knowledge_nodes WHERE user_id = ? AND node_type = "file" AND node_id = ?', [userId, file2.file_id]);

            if (sourceNodeId.length > 0 && targetNodeId.length > 0) {
              // 验证并转换关系类型
              const validTypes = ['similar_to', 'related_to', 'extends', 'references', 'depends_on'];
              let edgeType = similarity.relationshipType;
              
              if (!validTypes.includes(edgeType)) {
                console.warn(`无效的关系类型: ${edgeType}，使用默认值: related_to`);
                edgeType = 'related_to';
              }
              
              await query(`
                INSERT INTO knowledge_edges (user_id, source_node_id, target_node_id, edge_type, edge_weight, edge_properties)
                VALUES (?, ?, ?, ?, ?, ?)
              `, [
                userId,
                sourceNodeId[0].id,
                targetNodeId[0].id,
                edgeType,
                similarity.relationshipStrength,
                JSON.stringify({ reasons: similarity.reasons })
              ]);

              edges.push({
                source: file1.id,
                target: file2.id,
                type: similarity.relationshipType,
                weight: similarity.relationshipStrength,
                reasons: similarity.reasons
              });
            }
          }
        } catch (error) {
          console.error(`计算文件 ${file1.file_name} 和 ${file2.file_name} 相似度失败:`, error);
        }
      }
    }

    res.json({
      success: true,
      message: `知识图谱构建完成，发现 ${relationships.length} 个关联关系`,
      nodes: nodes,
      edges: edges,
      relationships: relationships
    });
  } catch (error) {
    console.error('构建知识图谱失败:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({
      success: false,
      message: '构建知识图谱失败',
      error: error.message
    });
  }
});

// 获取知识图谱数据
router.get('/graph', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取节点数据
    const nodes = await query(`
      SELECT kn.*, cf.file_name, cf.file_type, cf.file_size
      FROM knowledge_nodes kn
      LEFT JOIN cloud_files cf ON kn.node_type = 'file' AND kn.node_id = cf.id
      WHERE kn.user_id = ?
      ORDER BY kn.importance_score DESC
    `, [userId]);

    // 获取边数据
    const edges = await query(`
      SELECT ke.*, 
             source_kn.node_id as source_file_id,
             target_kn.node_id as target_file_id,
             source_cf.file_name as source_file_name,
             target_cf.file_name as target_file_name
      FROM knowledge_edges ke
      LEFT JOIN knowledge_nodes source_kn ON ke.source_node_id = source_kn.id
      LEFT JOIN knowledge_nodes target_kn ON ke.target_node_id = target_kn.id
      LEFT JOIN cloud_files source_cf ON source_kn.node_type = 'file' AND source_kn.node_id = source_cf.id
      LEFT JOIN cloud_files target_cf ON target_kn.node_type = 'file' AND target_kn.node_id = target_cf.id
      WHERE ke.user_id = ?
      ORDER BY ke.edge_weight DESC
    `, [userId]);

    // 格式化数据
    const formattedNodes = nodes.map(node => {
      let properties;
      try {
        properties = JSON.parse(node.node_properties || '{}');
      } catch (e) {
        console.log('解析node_properties失败:', node.node_properties);
        properties = {};
      }
      
      return {
        id: node.node_id,
        name: node.node_name,
        type: node.node_type,
        fileType: node.file_type,
        fileSize: node.file_size,
        description: node.node_description,
        properties: properties,
        importance: node.importance_score,
        group: node.node_type
      };
    });

    const formattedEdges = edges.map(edge => {
      let properties;
      try {
        properties = JSON.parse(edge.edge_properties || '{}');
      } catch (e) {
        console.log('解析edge_properties失败:', edge.edge_properties);
        properties = {};
      }
      
      return {
        source: edge.source_file_id,  // 使用文件ID而不是数据库节点ID
        target: edge.target_file_id,  // 使用文件ID而不是数据库节点ID
        type: edge.edge_type,
        weight: edge.edge_weight,
        properties: properties,
        sourceFileName: edge.source_file_name,
        targetFileName: edge.target_file_name
      };
    });

    res.json({
      success: true,
      nodes: formattedNodes,
      edges: formattedEdges,
      stats: {
        totalNodes: formattedNodes.length,
        totalEdges: formattedEdges.length,
        fileNodes: formattedNodes.filter(n => n.type === 'file').length
      }
    });
  } catch (error) {
    console.error('获取知识图谱失败:', error);
    res.status(500).json({
      success: false,
      message: '获取知识图谱失败'
    });
  }
});

// 获取文件关联详情
router.get('/file/:fileId/relationships', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const fileId = parseInt(req.params.fileId);

    // 获取文件信息
    const file = await query(`
      SELECT cf.*, fca.*
      FROM cloud_files cf
      LEFT JOIN file_content_analysis fca ON cf.id = fca.file_id
      WHERE cf.id = ? AND cf.user_id = ?
    `, [fileId, userId]);

    if (file.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }

    // 获取关联关系
    const relationships = await query(`
      SELECT fr.*, 
             cf.file_name as related_file_name,
             cf.file_type as related_file_type,
             cf.file_size as related_file_size
      FROM file_relationships fr
      JOIN cloud_files cf ON (
        CASE 
          WHEN fr.source_file_id = ? THEN fr.target_file_id = cf.id
          WHEN fr.target_file_id = ? THEN fr.source_file_id = cf.id
        END
      )
      WHERE (fr.source_file_id = ? OR fr.target_file_id = ?) AND fr.user_id = ?
      ORDER BY fr.similarity_score DESC
    `, [fileId, fileId, fileId, fileId, userId]);

    res.json({
      success: true,
      file: file[0],
      relationships: relationships.map(rel => ({
        ...rel,
        relationship_reasons: JSON.parse(rel.relationship_reasons || '[]')
      }))
    });
  } catch (error) {
    console.error('获取文件关联详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取文件关联详情失败'
    });
  }
});

module.exports = router;
